package com.base.starter.config;

import com.base.common.enums.TimeRegexEnum;
import com.base.common.exception.GlobalException;
import com.base.common.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.time.LocalDate;


/**
* @Description: 字符串转日期
* @Param:
* @return:
* @Author: zhou minghao
* @Date: 14:09 2024/4/23
*/
@Slf4j
public class LocalDateConverter implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(String source) {
        if (!StringUtils.hasText(source)) {
            return null;
        }
        for (TimeRegexEnum timePattern : TimeRegexEnum.values()) {
            if (source.matches(timePattern.getRegex())) {
                return TimeUtils.parseLocalDate(source, timePattern.getFormatter());
            }
        }
        log.error("字符串格式化成LocalDate失败，字符串：{}", source);
        throw new GlobalException("时间格式化失败");
    }
}
